package com.ruoyi.wechat.handler;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.wechat.domain.OnlineService;
import com.ruoyi.wechat.service.impl.OnlineServiceServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class ChatWebSocketHandler_bak extends TextWebSocketHandler {

    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
    private static final ConcurrentHashMap<String, WebSocketSession>  wxUserSessions = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, WebSocketSession> webUserSessions = new ConcurrentHashMap<>();

    @Autowired
    private OnlineServiceServiceImpl onlineServiceService;

    @Autowired
    private TokenService tokenService;

    @Value("${wechart.wxUserRole}")
    private String wxUserRole;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String token = getTokenFromSession(session);
        LoginUser loginUser = tokenService.getLoginUser(token);
        sessions.add(session);
        if (wxUserRole.equals(loginUser.getUser().getRoleId())) {
            wxUserSessions.put(token, session);
        } else {
            webUserSessions.put(token, session);
        }
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        String targetUserId = getTargetUserIdFromPayload(payload);

        WebSocketSession targetSession = null;
        String token = getTokenFromSession(session);
        LoginUser loginUser = tokenService.getLoginUser(token);

        // 插入消息
        if (loginUser != null && loginUser.getUser() != null) {

            message = new TextMessage(loginUser.getUser().getUserName() + ":" + payload);
        }

        if (wxUserRole.equals(loginUser.getUser().getRoleId())) {
            targetSession = wxUserSessions.get(targetUserId);

            if (targetSession != null && targetSession.isOpen()) {
                targetSession.sendMessage(message);
            }
        } else {
            targetUserId = "pcUser";
            // 遍历 webUserSessions，向所有webUserSessions发送消息
            for (String key : webUserSessions.keySet()) {
                targetSession = webUserSessions.get(key);
                if (targetSession != null && targetSession.isOpen()) {
                    targetSession.sendMessage(message);
                }
            }
        }
        OnlineService onlineService = new OnlineService();
        onlineService.setContent(payload);
        onlineService.setSenderId(getUserIdFromSession(session));
        onlineService.setReceiverId(targetUserId);
        onlineService.setState("0");
        onlineServiceService.insertOnlineService(onlineService);

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        String userId = getUserIdFromSession(session);
        wxUserSessions.remove(userId);
        webUserSessions.remove(userId);
    }

    private String getUserIdFromSession(WebSocketSession session) {
        // 从 session 中获取用户ID的逻辑
        return session.getUri().getQuery().split("=")[1];
    }
    private String getTokenFromSession(WebSocketSession session) {
        // 从 session 中获取用户Token的逻辑

        String token = session.getUri().getQuery().split("=")[1];
        token.replace(Constants.TOKEN_PREFIX, "");
        return token;
    }
    private String getTargetUserIdFromPayload(String payload) {
        // 从消息内容中提取目标用户ID的逻辑
        return payload.split(":")[0];
    }
}